package com.xnx3.kefu.inset.controller.admin;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.kefu.core.entity.Kefu;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.wangmarket.plugin.api.entity.InsetKefu;
import com.xnx3.wangmarket.plugin.api.util.SessionUtil;

/**
 * 三方平台登录客服管理后台
 * @author 管雷鸣
 */
@Controller(value="KefuInsetAdminLoginController")
@RequestMapping("/kefu/inset/admin/")
public class LoginController extends BaseController {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SqlCacheService sqlCacheService;

	/**
	 * 通过 token 登录客服管理平台
	 * @param password 64位， inset.password
	 * @return
	 */
	@RequestMapping(value="login${api.suffix}")
	public String login(HttpServletRequest request,Model model,
			@RequestParam(value = "password", required = false, defaultValue = "") String password){
		if(password.length() != 64){
			return error(model, "password长度错误");
		}
		InsetKefu inset = sqlCacheService.findAloneByProperty(InsetKefu.class, "password", password);
		if(inset == null){
			return error(model, "关联的客服不存在");
		}
		
		//正常，设置其登录成功，找到他管理的客服
		Kefu kefu = sqlCacheService.findById(Kefu.class, inset.getKefuid());
		
		//将kefu的userid变为已登录用户
		BaseVO vo = userService.loginForUserId(request, kefu.getUserid());
		ConsoleUtil.debug(vo.toString());
		
		//缓存客服信息
		SessionUtil.setKefu(kefu);
		//缓存第三方平台跟客户的绑定
		SessionUtil.setInsetKefu(inset);
		
		//登录成功后，将当前sessionid进行缓存，以便可以根据sessionid直接取User信息
		com.xnx3.kefu.core.util.SessionUtil.setActiveUserForNotRedis(request.getSession().getId(), SessionUtil.getActiveUser());
		
		return redirect("kefu/admin/index/index.jsp?token="+request.getSession().getId()+"&insetKefu=true");
	}
	
}
